var app = getApp();
const {
  $Toast
} = require('../../dist/base/index');
var common = require("../../utils/util.js");
var id;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    obj: {},
    number: 1,
    score: 0,
    isPickUpSelf: true,
    addressId: 0,
    addressInfo: {},
    nodes: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.getInfo(options.id)
    id = options.id;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    if (app.globalData.openId == "") {
      this.getOpenId();
    }
    //选择了地址
    if (this.data.addressId != 0) {
      var that = this;
      $Toast({
        content: '请稍候',
        type: 'loading',
        duration: 0,
      });
      wx.request({
        url: app.getUrl() + '/api/receive_info/receive_info',
        data: {
          infoId: this.data.addressId,
          Authorization: app.globalData.customerId + ":" + app.globalData.accessToken,
        },
        method: 'POST',
        header: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
        success(res) {
          $Toast.hide()
          if (res && res.statusCode == 200 && res.data && res.data.status == 200) {
            console.log(res)
            that.setData({
              addressInfo: res.data.obj,
            })
          } else {
            //token他处登录
            if (res.data.status == 403) {
              wx.showModal({
                title: '警告',
                content: '您的用户已在别的地方登录，是否重新登录？',
                success(res) {
                  if (res.confirm) {
                    wx.navigateTo({
                      url: '../login/login',
                    })
                  } else {}
                }
              })
            }
            // 没有登录状态
            else if (res.data.status == 406) {
              wx.switchTab({
                url: '../vipInfo/vipInfo',
                complete() {
                  wx.showToast({
                    title: '您还没有登录，请登录后查看',
                    icon: "none",
                    duration: 3000
                  })
                }
              })
            } else {
              $Toast({
                content: res.data.msg,
                type: 'warning',
                duration: 2,
              });
            }
          }
        },
        fail(res) {
          console.log(res)
          $Toast({
            content: '连接服务器失败',
            type: 'error',
            duration: 2,
          });
        }
      })
    } else {

    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  getOpenId() {
    var that = this;
    wx.login({
      success(res) {
        if (res.code) {
          $Toast({
            content: '请稍候',
            type: 'loading',
            duration: 0,
          });
          wx.request({
            url: app.getUrl() + '/api/customer/wxcx_openId',
            data: {
              code: res.code,
              Authorization: app.globalData.customerId + ":" + app.globalData.accessToken,
            },
            method: 'POST',
            header: {
              "Content-Type": "application/x-www-form-urlencoded",
            },
            success(res) {
              $Toast.hide()
              if (res && res.statusCode == 200 && res.data && res.data.status == 200) {
                if (res.data.obj && res.data.obj.openId){
                  app.globalData.openId = res.data.obj.openId;
                  try {
                    wx.setStorageSync('openId', res.data.obj.openId || "")
                  } catch (e) {
                    wx.setStorageSync('openId', "")
                  }
                }
              } else {
                //token他处登录
                if (res.data.status == 403) {
                  wx.showModal({
                    title: '警告',
                    content: '您的用户已在别的地方登录，是否重新登录？',
                    success(res) {
                      if (res.confirm) {
                        wx.navigateTo({
                          url: '../login/login',
                        })
                      } else {}
                    }
                  })
                }
                // 没有登录状态
                else if (res.data.status == 406) {
                  wx.switchTab({
                    url: '../vipInfo/vipInfo',
                    complete() {
                      wx.showToast({
                        title: '您还没有登录，请登录后查看',
                        icon: "none",
                        duration: 3000
                      })
                    }
                  })
                } else {
                  $Toast({
                    content: res.data.msg,
                    type: 'warning',
                    duration: 2,
                  });
                }
              }
            },
            fail(res) {
              console.log(res)
              $Toast({
                content: '连接服务器失败',
                type: 'error',
                duration: 2,
              });
            }
          })
        } else {
          $Toast({
            content: '登录失败！',
            type: 'warning',
            duration: 2,
          });
          console.log('登录失败！' + res.errMsg)
        }
      }
    })
  },
  getInfo(id) {
    $Toast({
      content: '请稍候',
      type: 'loading',
      duration: 0,
    });
    var that = this;
    wx.request({
      url: app.getUrl() + '/api/exchange_record/gift_info',
      data: {
        giftId: id,
        Authorization: app.globalData.customerId + ":" + app.globalData.accessToken,
      },
      method: 'POST',
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      success(res) {
        $Toast.hide()
        if (res && res.statusCode == 200 && res.data && res.data.status == 200) {
          that.setData({
            obj: res.data.obj,
            isPickUpSelf: res.data.obj.isPickUpSelf,
          })
          if (res.data.obj.giftDetail) {
            that.setData({
              nodes: res.data.obj.giftDetail.replace(/\<img/g, "<img style='max-width:100%;height:auto;display:block;border-radius: 10px;'  lazy-load='true'")
            })
          }
          that.computeScore()
        } else {
          //token他处登录
          if (res.data.status == 403) {
            wx.showModal({
              title: '警告',
              content: '您的用户已在别的地方登录，是否重新登录？',
              success(res) {
                if (res.confirm) {
                  wx.navigateTo({
                    url: '../login/login',
                  })
                } else {}
              }
            })
          }
          // 没有登录状态
          else if (res.data.status == 406) {
            wx.switchTab({
              url: '../vipInfo/vipInfo',
              complete() {
                wx.showToast({
                  title: '您还没有登录，请登录后查看',
                  icon: "none",
                  duration: 3000
                })
              }
            })
          } else {
            $Toast({
              content: res.data.msg,
              type: 'warning',
              duration: 2,
            });
          }
        }
      },
      fail(res) {
        console.log(res)
        $Toast({
          content: '连接服务器失败',
          type: 'error',
          duration: 2,
        });
      }
    })
  },
  add() {
    this.setData({
      number: this.data.number + 1
    })
    this.computeScore()
  },
  sub() {
    if (this.data.number > 1) {
      this.setData({
        number: this.data.number - 1
      })
      this.computeScore()
    } else {}
  },
  computeScore() {
    this.setData({
      score: common.formatFloat(this.data.number, this.data.obj.integral)
    })
  },
  selectAddress() {
    wx.navigateTo({
      url: "../xzdz/xzdz?from='select'",
    })
  },
  sure(e) {
    var that = this;
    console.log(e)
    // console.log(this.data.score)
    // console.log(id)
    // console.log(this.data.number)
    // console.log(this.data.addressId)
    // console.log(this.data.isPickUpSelf)

    //是自提礼品，不用验证是否填写地址
    if (this.data.isPickUpSelf) {
      var that = this;
      wx.showModal({
        title: '提示',
        content: '您选择的礼品需要前往就近麦田云网点自提，确认兑换吗？',
        success(res) {
          if (res.confirm) {
            wx.showLoading({
              title: '请稍候',
              mask: true
            })
            wx.request({
              url: app.getUrl() + '/api/exchange_record/exchange_gift',
              data: {
                giftId: id,
                exchangeCount: that.data.number,
                Authorization: app.globalData.customerId + ":" + app.globalData.accessToken,
                formId: e.detail.formId,
              },
              method: 'POST',
              header: {
                "Content-Type": "application/x-www-form-urlencoded",
              },
              success(res) {
                wx.hideLoading();
                if (res && res.statusCode == 200 && res.data && res.data.status == 200) {
                  wx.redirectTo({
                    url: '../dhjl/dhjl',
                    success(res) {
                      $Toast({
                        content: '兑换成功',
                        type: 'success',
                        duration: 2,
                      });
                    }
                  })
                } else {
                  //token他处登录
                  if (res.data.status == 403) {
                    wx.showModal({
                      title: '警告',
                      content: '您的用户已在别的地方登录，是否重新登录？',
                      success(res) {
                        if (res.confirm) {
                          wx.navigateTo({
                            url: '../login/login',
                          })
                        } else {}
                      }
                    })
                  }
                  // 没有登录状态
                  else if (res.data.status == 406) {
                    wx.switchTab({
                      url: '../vipInfo/vipInfo',
                      complete() {
                        wx.showToast({
                          title: '您还没有登录，请登录后查看',
                          icon: "none",
                          duration: 3000
                        })
                      }
                    })
                  } else {
                    $Toast({
                      content: res.data.msg,
                      type: 'warning',
                      duration: 2,
                    });
                  }
                }
              },
              fail(res) {
                console.log(res)
                wx.showToast({
                  title: '连接服务器失败',
                  icon: "none",
                  duration: 2
                })
              }
            })
          } else {}
        }
      })
    } else { //不是自提礼品需要验证是否选择了收货地址
      if (this.data.addressId == 0) {
        $Toast({
          content: '请填写收货地址',
          type: 'warning',
          duration: 2,
        });
      } else {
        var that = this;
        wx.showModal({
          title: '提示',
          content: '确认兑换吗？',
          success(res) {
            if (res.confirm) {
              wx.showLoading({
                title: '请稍候',
                mask: true
              })
              wx.request({
                url: app.getUrl() + '/api/exchange_record/exchange_gift',
                data: {
                  giftId: id,
                  exchangeCount: that.data.number,
                  infoId: that.data.addressId,
                  Authorization: app.globalData.customerId + ":" + app.globalData.accessToken,
                  formId: e.detail.formId,
                },
                method: 'POST',
                header: {
                  "Content-Type": "application/x-www-form-urlencoded",
                },
                success(res) {
                  wx.hideLoading();
                  if (res && res.statusCode == 200 && res.data && res.data.status == 200) {
                    wx.redirectTo({
                      url: '../dhjl/dhjl',
                      success(res) {
                        $Toast({
                          content: '兑换成功',
                          type: 'success',
                          duration: 2,
                        });
                      }
                    })
                  } else {
                    //token他处登录
                    if (res.data.status == 403) {
                      wx.showModal({
                        title: '警告',
                        content: '您的用户已在别的地方登录，是否重新登录？',
                        success(res) {
                          if (res.confirm) {
                            wx.navigateTo({
                              url: '../login/login',
                            })
                          } else {}
                        }
                      })
                    }
                    // 没有登录状态
                    else if (res.data.status == 406) {
                      wx.switchTab({
                        url: '../vipInfo/vipInfo',
                        complete() {
                          wx.showToast({
                            title: '您还没有登录，请登录后查看',
                            icon: "none",
                            duration: 3000
                          })
                        }
                      })
                    } else {
                      $Toast({
                        content: res.data.msg,
                        type: 'warning',
                        duration: 2,
                      });
                    }
                  }
                },
                fail(res) {
                  console.log(res)
                  wx.showToast({
                    title: '连接服务器失败',
                    icon: "none",
                    duration: 2
                  })
                }
              })
            } else {}
          }
        })
      }
    }
  }
})